package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueDayStatsAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionVehicleAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.CustomerExtAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.request.SyncCrmUpdateClueRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryCertificateInfoRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleModelRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleSeriesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.*;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.IMsgTodoClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.request.CustomButtonRequest;
import com.tencent.iov.cowin.befsale.clue.dao.kafka.KafkaConfig;
import com.tencent.iov.cowin.befsale.clue.dao.kafka.response.ScrmLead;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.*;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.*;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.CustomerExt;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomer;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.PurchaseInvoiceInfo;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.*;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueIntentionVehicleRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.ClueFollowUpRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.QueryClueRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.UpdateClueIntentionRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.*;
import com.tencent.iov.cowin.befsale.clue.service.clue.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Describe: 线索信息表_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:03
 * @version: 1.0
 */
@Service
@Slf4j
public class ClueServiceImpl implements ClueService {

    @Autowired
    private ClueManager clueManager;
    @Autowired
    private ClueIntentionService clueIntentionService;
    @Autowired
    private OemCustomerService oemCustomerService;
    @Autowired
    private OemCustomerFollowRecordService oemCustomerFollowRecordService;
    @Autowired
    private OemCustomerFollowPlanService oemCustomerFollowPlanService;
    /* @Autowired
     private OemCustomerTagRelService oemCustomerTagRelService;*/
    @Autowired
    private DealerCustomerService dealerCustomerService;
    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;
    @Autowired
    private DealerCustomerFollowPlanService dealerCustomerFollowPlanService;
    @Autowired
    private ClueCustomerCollectService clueCustomerCollectService;
    @Autowired
    private CustomerExtService customerExtService;
    @Autowired
    private ClueIntentionVehicleService clueIntentionVehicleService;
    @Autowired
    private ClueFailService clueFailService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerFollowRecordService customerFollowRecordService;
    @Autowired
    private TenantClient tenantClient;
    @Autowired
    private MdQueryClient mdQueryClient;
    @Autowired
    private CrmService crmService;
    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private ClueInitialService clueInitialService;
    @Autowired
    private SyncClueBuriedPintService syncClueBuriedPintService;
    @Autowired
    private IMsgTodoClient msgTodoClient;
    @Autowired
    private PurchaseInvoiceInfoService purchaseInvoiceInfoService;

    @Value("${clue-todo.template.msgTodoFollowClue.id}")
    private Long followTodoId;
    @Value("${clue-todo.template.todoAssignId.id}")
    private Long todoAssignId;
    //crm的tenant
    @Value("${properties.default.tenant-id}")
    private String tenandId;
    //crm的corp
    @Value("${properties.default.corp-id}")
    private String corpId;
    //同步战败给crm，默认战败类型为其它
    @Value("${scrm.defaultFailType}")
    private Integer defaultFailType;
    //同步crm视图信息，默认这几家进销商的线索，不同步crm的战败和交车，多个以逗号隔开
    @Value("${scrm.defaultDealerId}")
    private String defaultDealerId;

    //创建一个定长线程池，超出的线程会在队列中等待
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);


    /**
     * 通过ID获取详细信息
     *
     * @param: request
     * @return: Clue对象
     */
    @Override
    public Clue getDetailById(Long id) {
        /** 1 验证请求参数 */
        ValidateUtils.checkLongGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        Clue clue = clueManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clue)) {
            return BeanUtil.copy(clue, Clue.class);
        }
        /** 3 返回结果 */
        return null;
    }

    @Override
    public Clue getDetailByExternalUserIdAndFollowEmpId(String externalUserId, Long followEmpId) {
        QueryCustomerRequest queryCustomer = new QueryCustomerRequest();
        queryCustomer.setFollowEmpId(followEmpId);
        queryCustomer.setDeleted(DeleteEnum.INIT.getFlag());
        queryCustomer.setExternalUserid(externalUserId);

        //客户信息
        List<CustomerResponse> customers = customerService.getListByParam(queryCustomer);
        if (EmptyUtils.isEmpty(customers)) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "未绑定客户信息");
        }
        List<Long> cusIds = customers.stream().map(CustomerResponse::getId).collect(Collectors.toList());
        Clue queryClue = new Clue();
        queryClue.setCusIds(cusIds);
        queryClue.setDeleted(DeleteEnum.INIT.getFlag());
        queryClue.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        OrderField orderField = new OrderField("id", "desc");
        queryClue.setOrderFields(Lists.newArrayList(orderField));
        List<Clue> clues = clueManager.getListByParam(queryClue);
        if (EmptyUtils.isEmpty(clues)) {
            return null;
        }
        List<Clue> activeClues = clues.stream().filter(clue -> IsActiveEnum.ACTIVE_YES.getCode().equals(clue.getIsActive())).collect(Collectors.toList());
        if (EmptyUtils.isNotEmpty(activeClues)) {
            return activeClues.get(0);
        }
        return clues.get(0);
    }

    /**
     * 单条数据插入Clue
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public int insert(Clue request) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueManager.insert(request);
        /** 3 封装返回值 */
        return count;
    }

    /**
     * 批量插入Clue
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<Clue> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    /**
     * 单条Clue更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(Clue request) {

        /** 1 验证请求参数 */
        /** 2 处理业务 */
        request = ClueAssembler.initUpdateClue(request);
        int count = clueManager.update(request);
        /** 3 返回对象 */
        return count;
    }

    @Override
    public int updateByIds(Clue request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request.getIds(), "IDS不能为空或小于0");
        /** 2 处理业务 */
        /** 3 返回对象 */
        return clueManager.updateByIds(request);
    }


    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(Clue request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        Clue clue = new Clue();
        clue.setId(id);
//		clue.setDelete(DeleteEnum.DETELED.getCode());
        int count = clueManager.update(clue);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<Clue> getListByParam(Clue request) {
        /** 1 验证请求参数 */
        //可以设置排序
        /** 2 处理业务 */
        List<Clue> queryList = clueManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, Clue.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<Clue> getPageByParam(PageRequest<Clue> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
        Page<Clue> queryPageList = clueManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<Clue> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), Clue.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    /**
     * 线索下发-创建线索  add by zly 2021-12-23
     *
     * @param request
     * @return
     */

    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public Long createClueWithfollowUp(ClueFollowUpRequest request, Integer sendType) {
        //获取 线索源对应的经销商id
        String dealerId = request.getDealerId();
        Date currentDate=new Date();
        //第一步：保存客户信息，获得客户主键
        Long oemCustomerId = null;
        Long dealerCustomerId = null;
        Long exitsFollowEmpId=null;
        String exitsFollowEmpName="";
        //保存客户基本信息到 bef_oem_customer表
        OemCustomer oemCustomer = OemCustomerAssembler.transformVOToPO(request.getFollowUpCustomer(), OemCustomer.class);
        //根据客户入参数据判断是否完善字段
        if(EmptyUtils.isNotEmpty(oemCustomer.getExternalUserid())){
            oemCustomer.setBindTime(currentDate);
        }
        //定义埋点需要数据
        CustomerResponse pointCusResponse = null;

        //验证该followempId下的客户是否存在，存在拿到对应的id,做信息修改，不存在则新增
        OemCustomer oemCustomerSearch = new OemCustomer();
        oemCustomerSearch.setTenantId(oemCustomer.getTenantId());
        oemCustomerSearch.setCorpId(oemCustomer.getCorpId());
       // oemCustomerSearch.setFollowEmpId(oemCustomer.getFollowEmpId());
        oemCustomerSearch.setOneId(oemCustomer.getOneId());
       // oemCustomerSearch.setPhone(oemCustomer.getPhone());
        CustomerResponse customerResponse = oemCustomerService.getOneByParam(oemCustomerSearch);
        if (customerResponse == null) {
            pointCusResponse = BeanUtil.copy(oemCustomer, CustomerResponse.class);
            oemCustomerService.insert(oemCustomer);
            //跟进人不为空，说明已经分配顾问
            if (!StringUtils.isEmpty(oemCustomer.getFollowEmpId())&&!"-1".equals(oemCustomer.getFollowEmpId())) {
                request.getFollowUpClue().setDealerFollowStatus(DealerFollowStatusEnum.DISTRIBUTION_ADVISER.getCode());
            } else {
                request.getFollowUpClue().setDealerFollowStatus(DealerFollowStatusEnum.WAIT_DISTRIBUTION.getCode());
            }
            oemCustomerId = oemCustomer.getId();
        } else {
            //存在则修改
            exitsFollowEmpId=customerResponse.getFollowEmpId();
            exitsFollowEmpName=customerResponse.getFollowEmpName();
            oemCustomerId = customerResponse.getId();
            oemCustomer.setId(oemCustomerId);
            pointCusResponse = BeanUtil.copy(oemCustomer, CustomerResponse.class);

            oemCustomerService.updateById(oemCustomer);
        }
        if (!StringUtils.isEmpty(dealerId) && !"0".equals(dealerId)) {
            //保存经销商客户 到 bef_dealer_customer
            AddDealerCustomerRequest dealerCustomer = DealerCustomerAssembler.transformVOToPO(request.getFollowUpCustomer(), AddDealerCustomerRequest.class);
            //根据客户入参数据判断是否完善字段
            if(EmptyUtils.isNotEmpty(dealerCustomer.getExternalUserid())){
                dealerCustomer.setBindTime(currentDate);
            }

            dealerCustomer.setDealerId(dealerId);
            dealerCustomer.setOemCusId(oemCustomerId);
            //查看对应的客户是否存在，存在则修改，不存在则新增
            QueryCustomerRequest dealerCustomerSearch = new QueryCustomerRequest();
            dealerCustomerSearch.setTenantId(dealerCustomer.getTenantId());
            dealerCustomerSearch.setCorpId(dealerCustomer.getCorpId());
            dealerCustomerSearch.setDealerId(dealerCustomer.getDealerId());
           // dealerCustomerSearch.setFollowEmpId(dealerCustomer.getFollowEmpId());
            dealerCustomerSearch.setOneId(dealerCustomer.getOneId());
            dealerCustomerSearch.setDeleted(DeletedEnum.EXIST.getCode());
            //dealerCustomerSearch.setPhone(dealerCustomer.getPhone());
           // dealerCustomerSearch.setOemCusId(dealerCustomer.getOemCusId());
            CustomerResponse dealerSearchRes = dealerCustomerService.getOneByParam(dealerCustomerSearch);
            if (dealerSearchRes == null) {
                pointCusResponse = BeanUtil.copy(oemCustomer, CustomerResponse.class);
                //经销商客户主键id
                dealerCustomerId = dealerCustomerService.insert(dealerCustomer);
                //跟进人不为空，说明已经分配顾问
                if (!StringUtils.isEmpty(dealerCustomer.getFollowEmpId())&&!"-1".equals(dealerCustomer.getFollowEmpId())) {
                    request.getFollowUpClue().setDealerFollowStatus(DealerFollowStatusEnum.DISTRIBUTION_ADVISER.getCode());
                } else {
                    request.getFollowUpClue().setDealerFollowStatus(DealerFollowStatusEnum.DISTRIBUTION_DEALER.getCode());
                }
            } else {
                exitsFollowEmpId=customerResponse.getFollowEmpId();
                exitsFollowEmpName=customerResponse.getFollowEmpName();
                dealerCustomerId = dealerSearchRes.getId();
                UpdateCustomerRequest dealerCustomerRequest = DealerCustomerAssembler.transformVOToPO(dealerCustomer, UpdateCustomerRequest.class);
                dealerCustomerRequest.setId(dealerCustomerId);
                pointCusResponse = BeanUtil.copy(oemCustomer, CustomerResponse.class);
                dealerCustomerService.update(dealerCustomerRequest);
            }
            //下发时间set
            if (EmptyUtils.isEmpty(request.getFollowUpClue().getPlanTime())) {
                request.getFollowUpClue().setPlanTime(currentDate);
            }

        }
        //保存客户扩展信息
        if (request.getFollowUpCustomerExt() != null) {
            CustomerExt customerExt = CustomerExtAssembler.transformVOToPO(request.getFollowUpCustomerExt(), CustomerExt.class);
            if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
                customerExt.setCustomerType(CustomerTypeEnum.CUSTOMER_TYPE_OEM.getCode());
                customerExt.setCusId(oemCustomerId);
            } else {
                customerExt.setDealerId(dealerId);
                customerExt.setCustomerType(CustomerTypeEnum.CUSTOMER_TYPE_DEALER.getCode());
                customerExt.setCusId(dealerCustomerId);
            }
            //查看客户扩展信息是否存在，不存在则新增，存在则修改
            CustomerExt cusExtSearch = new CustomerExt();
            cusExtSearch.setTenantId(customerExt.getTenantId());
            cusExtSearch.setCorpId(customerExt.getCorpId());
            cusExtSearch.setDealerId(customerExt.getDealerId());
            cusExtSearch.setCusId(customerExt.getCusId());
            CustomerExt cusExtRes = customerExtService.getOneByParam(cusExtSearch);
            if (cusExtRes == null) {
                customerExtService.insert(customerExt);
            } else {
                customerExt.setId(cusExtRes.getId());
                customerExtService.update(customerExt);
            }
        }

        // 第二步：保存线索信息  bef_clue 表
        Clue clue = ClueAssembler.transformVOToPO(request.getFollowUpClue(), Clue.class);
        clue.setId(clue.getClueInitialId());//线索源id和线索id同步成一个字段，本身的线索源id后期不要了
        if(ClueStatsEnum.FOLLOW_UP.getCode()==clue.getStatus()||
                ClueStatsEnum.CHECKIN.getCode()==clue.getStatus()||
                ClueStatsEnum.FAIL_APPROVE.getCode()==clue.getStatus()) {
            clue.setIsActive(IsActiveEnum.ACTIVE_YES.getCode());
        }else{
            clue.setIsActive(IsActiveEnum.ACTIVE_NO.getCode());
        }
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            clue.setCusId(oemCustomerId);
        } else {
            clue.setDealerId(dealerId);
            clue.setCusId(dealerCustomerId);
        }
        if(!StringUtils.isEmpty(exitsFollowEmpName)){
            clue.setDistributeTime(currentDate);
            request.getFollowUpClue().setDistributeTime(currentDate);
            clue.setDealerFollowStatus(DealerFollowStatusEnum.DISTRIBUTION_ADVISER.getCode());
        }
        //验证线索是否存在，存在则修改，不存在则新增
        Clue clueCheck=new Clue();
        clueCheck.setCrmClueId(clue.getCrmClueId());
        clueCheck.setId(clue.getClueInitialId());
        clueCheck.setDeleted(DeleteEnum.INIT.getFlag());
        Clue clueChekResult= clueManager.getOneByParam(clueCheck);
        //存在则修改
        if(clueChekResult!=null){
            clueManager.update(clue);
        }else {
            clueManager.insert(clue);
        }
        //线索主键id
        Long clueId = clue.getId();
        request.setClueId(clueId);
        request.setOemCustomerId(oemCustomerId);
        request.setDealerCustomerId(dealerCustomerId);
        request.setExitsFollowEmpId(exitsFollowEmpId);
        request.setExitsFollowEmpName(exitsFollowEmpName);

        //3代表从crm同步过来的老数据，所以不发待办，不做埋点。
        if(sendType!=3) {
            //添加埋点
            syncClueBuriedPintService.addClueBuriedPint(request, clue, pointCusResponse);
            //对接代办
            processFollowTodoParam(request);
        }
        return clueId;
    }


    private void processFollowTodoParam(ClueFollowUpRequest request) {
        String corpId = request.getFollowUpClue().getCorpId();
        String tenantId = request.getFollowUpClue().getTenantId();
        String name = request.getFollowUpCustomer().getName();
        String phone = request.getFollowUpCustomer().getPhone();
        Long clueId = request.getClueId();

        //如果线索没有跟进人，则发 待分配待办
        Long followEmpId=request.getFollowUpCustomer().getFollowEmpId();
        if(followEmpId==null||followEmpId==-1){
            //默认时间是24H后
            Date date = DateUtil.addHours(new Date(), 24);
            String dealerId=request.getDealerId();
            //说明是经销商--未分配
            /*if(!StringUtils.isEmpty(dealerId) && !"0".equals(dealerId)){
                date = new Date();
            }*/
            if(!StringUtils.isEmpty(dealerId) && !"0".equals(dealerId)) {
                //根据经销商id查看对应的所有顾问
                Response<List<Long>> empRes= mdQueryClient.queryEmpIdsByDealerId(Integer.parseInt(dealerId));
                log.info("根据经销商id获取对应的顾问id集合，dealerId={},返回信息empRes={}",dealerId,JSON.toJSONString(empRes));
                if(empRes!=null&&empRes.getData()!=null&&empRes.getData().size()>0) {
                    List<Long> empIds=empRes.getData();
                    makeTodoAssignClue(date, empIds, "", name, phone, clueId, tenantId, corpId, request.getFollowUpCustomer().getExternalUserid());

                }
            }
        }else {
            //否则发待跟进待办
            log.info("设置下次跟进时间对接待办");
            Date date = DateUtil.addHours(new Date(), 24);
            List<Long> empIds = new ArrayList<>();
            empIds.add(followEmpId);

            if (request.getFollowUpPlan().getPlanFollowTime() != null) {
                date = request.getFollowUpPlan().getPlanFollowTime();
            }

            String followContent = request.getFollowUpPlan().getPlanFollowContent();
            String content = followContent == null ? "产品介绍" : FollowContentEnum.getDictionaries(Integer.valueOf(followContent));


            makeFollowTodoTask(date, empIds, content, name, phone, clueId, tenantId, corpId, request.getFollowUpCustomer().getExternalUserid());
        }
    }


    /**
     * 线索下发新增--参数验证
     * add by zly
     *
     * @param request
     * @return
     */
    public ClueErrorEnum checkClueFollowUp(ClueFollowUpRequest request) {
        if (request.getFollowUpCustomer() == null) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CUSTOMER_ERROR;
        }
        if (request.getFollowUpClue() == null) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CLUE_ERROR;
        }

       /* if (StringUtils.isEmpty(request.getFollowUpCustomer().getSourceSecond())) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CUSTOMER_SOURCESECOND_ERROR;
        }*/

        //验证线索下发oneId是否为空
        if (StringUtils.isEmpty(request.getFollowUpCustomer().getOneId())) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CUSTOMER_ONEID_ERROR;
        }

        if (StringUtils.isEmpty(request.getFollowUpCustomer().getName())) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CUSTOMER_NAME_ERROR;
        }

        //验证客户是否存在活跃线索，若存在，则不允许创建
        boolean falg = oemCustomerService.checkCustomerPhone(request.getFollowUpCustomer().getPhone(), request.getDealerId(),
                request.getFollowUpClue().getTenantId(),request.getFollowUpClue().getCorpId());
        if (falg) {
            return ClueErrorEnum.CLUE_FOLLOWUP_CUSTOMER_ISACTIVE_ERROR;
        }
        return null;
    }


    /**
     * 线索下发新增--参数验证
     * add by zly
     *
     * @param clueInitial
     * @return
     */
    public ClueErrorEnum cleanClueCheck( ClueInitial clueInitial) {
        if (InitialStatusEnum.STATUS_DEAL_WITH.getCode()==clueInitial.getStatus()) {
            return ClueErrorEnum.CLUE_CLEAN_CHECK001_ERROR;
        }
        return null;
    }

    @Override
    public void makeFollowTodoTask(Date date, List<Long> empIds, String content, String name, String phone, Long clueId,String tenantId,String corpId,String externalUserid) {
        String dateStr = DateUtil.toDateString(date, "yyyy-MM-dd HH:mm");
        Map<String, Object> todoMap = new HashMap<>();
        todoMap.put("time", dateStr);
        todoMap.put("content", content);
        todoMap.put("name", name);
        todoMap.put("phone", phone);
        List<CustomButtonRequest> buttonRequestList = new ArrayList<>();
        CustomButtonRequest customButtonRequest = new CustomButtonRequest();
        customButtonRequest.setName(MsgTodoEnum.BTN_FOLLOW_CLUE.getName());
        customButtonRequest.setEvent(MsgTodoEnum.BTN_FOLLOW_CLUE.getCode());
        customButtonRequest.setUrl("/clue/adviser/detail?id=" + clueId);
        buttonRequestList.add(customButtonRequest);

        String title = "待跟进线索-" + name;
        String cont = "计划跟进:" + dateStr +
                "|" + content + "\n客户:" + name + "|" + phone;

        clueFailService.makeTodoTask(buttonRequestList, followTodoId, title, cont, MsgTodoEnum.FOLLOW_CLUE.getCode(), empIds, todoMap, date, clueId,phone,tenantId,corpId,externalUserid);
    }

    @Override
    public void makeTodoAssignClue(Date date, List<Long> empIds, String content, String name, String phone, Long clueId,String tenantId,String corpId,String externalUserid) {
        Date currentDate=new Date();
        String currentDateStr=DateUtil.toDateString(currentDate, "yyyy-MM-dd HH:mm");
        Map<String, Object> todoMap = new HashMap<>();
        todoMap.put("time", currentDateStr); // 消息中心的
        todoMap.put("content", content);
        todoMap.put("name", name);
        todoMap.put("phone", phone);
        List<CustomButtonRequest> buttonRequestList = new ArrayList<>();
        CustomButtonRequest customButtonRequest = new CustomButtonRequest();
        customButtonRequest.setName(MsgTodoEnum.BTN_ASSIGN_CLUE.getName());
        customButtonRequest.setEvent(MsgTodoEnum.BTN_ASSIGN_CLUE.getCode());
        customButtonRequest.setUrl("/clue/adviser/detail?id="+clueId+"&disabled=true&type=5");
        buttonRequestList.add(customButtonRequest);
        //线索下发时间即当前时间：

        String title = "待分配线索-" + name;
        String cont = "线索下发:" + currentDateStr +
                "|" + content + "\n客户:" + name + "|" + phone;

        clueFailService.makeTodoTask(buttonRequestList, todoAssignId, title, cont, MsgTodoEnum.ASSIGN_CLUE.getCode(), empIds, todoMap, date, clueId,phone,tenantId,corpId,externalUserid);
    }


    @Override
    public Boolean updateClueAndIntention(UpdateClueIntentionRequest request) {
        ValidateUtils.checkLongGTZero(request.getId(), "意向ID参数错误");
        ValidateUtils.checkLongGTZero(request.getClueId(), "线索ID参数错误");

        Clue existClue = clueManager.getDetailById(request.getClueId());
        if (EmptyUtils.isEmpty(existClue)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索信息不存在");
        }

        //更新线索信息
        Clue updateClue = BeanUtil.copy(request, Clue.class);
        if (EmptyUtils.isNotEmpty(updateClue)) {
            updateClue.setId(request.getClueId());
            updateClue = ClueAssembler.initUpdateClue(updateClue);
            int cluResult = clueManager.update(updateClue);
            if (cluResult <= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "更新线索信息失败");
            }
        }

        //添加或线索意向车的信息
        List<ClueIntentionVehicle> clueIntentionVehicles = insertClueIntentionVehicle(request);

        //更新意向信息
        ClueIntention clueIntention = updateClueIntention(request);

        //添加跟进记录
        String clueIntentionStr = clueIntentionService.getClueIntentionStr(clueIntention);
        AddCustomerFollowRecordRequest followRecord = DealerCustomerFollowRecordAssembler
                .initAddByIntentionChange(clueIntentionStr, existClue, request, clueIntentionVehicles);
        Long followResult = customerFollowRecordService.insert(followRecord);
        if (EmptyUtils.isEmpty(followResult) || followResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "保存跟进信息失败");
        }
        return true;
    }

    private ClueIntention updateClueIntention(UpdateClueIntentionRequest request) {
        ClueIntention clueIntention = clueIntentionService.getDetailById(request.getId());
        if (EmptyUtils.isEmpty(clueIntention) || DeleteEnum.DETELED.getFlag().equals(clueIntention.getDeleted())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "意向信息修正-线索意向信息不存在");
        }

        ClueIntentionAssembler.initUpdateByClueIntention(request, clueIntention);
        int cluResult = clueIntentionService.update(clueIntention);
        if (cluResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新意向信息失败");
        }
        return clueIntention;
    }

    private List<ClueIntentionVehicle> insertClueIntentionVehicle(UpdateClueIntentionRequest request) {
        List<AddClueIntentionVehicleRequest> addClueIntentionVehicleRequests = Lists.newArrayList();
        if (EmptyUtils.isEmpty(request.getClueIntentionVehicles())) {
            ClueIntentionVehicle query = new ClueIntentionVehicle();
            query.setClueId(request.getClueId());
            query.setDeleted(DeleteEnum.INIT.getFlag());
            return clueIntentionVehicleService.getListByParam(query);
        }
        for (int i = 0; i < request.getClueIntentionVehicles().size(); i++) {
            if (request.getClueIntentionVehicles().get(i) instanceof AddClueIntentionVehicleRequest) {
                addClueIntentionVehicleRequests.add(ClueIntentionVehicleAssembler.initAddClueIntentionVehicleRequest(request.getClueIntentionVehicles().get(i)));
            }
        }
        request.setClueIntentionVehicles(addClueIntentionVehicleRequests);
        List<ClueIntentionVehicle> clueIntentionVehicles = BeanUtil.copyByList(addClueIntentionVehicleRequests, ClueIntentionVehicle.class);
        int insertVehResult = clueIntentionVehicleService.insertBatch(clueIntentionVehicles);
        if (insertVehResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "处理意向车系车型信息失败");
        }
        return clueIntentionVehicles;
    }

    @Override
    public Clue getOneByParam(Clue request) {
        return clueManager.getOneByParam(request);
    }

    /**
     * 管理看板-线索看板
     * add by zly 2022-01-11
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public ClueIntentionGradeResponse getClueIntentionGradeData(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        //赋值租户，企微，经销商
        ClueAssembler.initClueIntentionGradeDataRequest(clueIntentionGradeDataRequest);
        clueIntentionGradeDataRequest = this.initStartTimeEndTime(clueIntentionGradeDataRequest);
        log.info("管理看板-线索看板方法调用参数request={}", JSON.toJSONString(clueIntentionGradeDataRequest));
        List<ClueIntentionGrade> clueIGList=clueManager.getClueIntentionGradeData(clueIntentionGradeDataRequest);
        log.info("管理看板-线索看板方法查询数据库返回 clueIGList={}", JSON.toJSONString(clueIGList));
        ClueIntentionGradeResponse result=new ClueIntentionGradeResponse();
        result.setEndTime(clueIntentionGradeDataRequest.getEndTime());

        //查询获取意向字典信息
        QueryDictionariesRequest request = new QueryDictionariesRequest();
        request.setType(DictionariesEnum.CLUE_INTENTION_GRADE.getType());
        List<OrderField> orderFields = new ArrayList();
        OrderField field = new OrderField("id","asc");
        orderFields.add(field);
        request.setOrderFields(orderFields);
        Response<List<DictionariesResponse>> dicResponse = tenantClient.getDictionariesListByParam(request);
        log.info("管理看板-线索看板方法调用字典 dicResponse={}", JSON.toJSONString(dicResponse));
        if(dicResponse==null||dicResponse.getData()==null||dicResponse.getData().size()==0){
            result.setClueIGList(clueIGList);
            return result;
        }
        List<DictionariesResponse> dicList=dicResponse.getData();
        Map<String, String> dicMap =dicList.stream().collect(Collectors.toMap(r -> r.getCode(), r -> r.getName()));
        log.info("管理看板-线索看板方法调用字典 map={}", JSON.toJSONString(dicMap));
        //获取字典code对应的名称
        if(CollectionUtils.isNotEmpty(clueIGList)) {
            clueIGList.stream().forEach(g->{
                if(!StringUtils.isEmpty(g.getIntentionGrade())){
                    g.setName(dicMap.get(g.getIntentionGrade()));
                }
            });
        }

        List<String> orderList = dicList.stream().map(item -> item.getCode()).collect(Collectors.toList());
        Collections.sort(clueIGList, new Comparator<ClueIntentionGrade>() {
            @Override
            public int compare(ClueIntentionGrade o1, ClueIntentionGrade o2) {
                int io1 = orderList.indexOf(o1.getIntentionGrade());
                int io2 = orderList.indexOf(o2.getIntentionGrade());
                return io1 - io2;
            }
        });

        result.setClueIGList(clueIGList);
        return result;
    }

    @Override
    public ClueIntentionGradeDataRequest initStartTimeEndTime(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        try {
            Instant currentDate = Instant.now();
            clueIntentionGradeDataRequest.setEndTime(new Date(currentDate.toEpochMilli()));
            //时间计算
            DataSearchTypeEnum dataSearchTypeEnum = clueIntentionGradeDataRequest.getDataSearchTypeEnum();
            if (dataSearchTypeEnum == null || DataSearchTypeEnum.SEARCH_TYPE_All.getCode().equals(dataSearchTypeEnum.getCode())) {
                //全部
                clueIntentionGradeDataRequest.setStartTime(null);
            } else if (DataSearchTypeEnum.SEARCH_TYPE_CURRENT_MONTH.getCode().equals(dataSearchTypeEnum.getCode())) {
                //当月
                LocalDate localDate = YearMonth.from(currentDate.atZone(ZoneId.of("UTC"))).atDay(1);
                Date curentMonthFirstDay = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
                clueIntentionGradeDataRequest.setStartTime(curentMonthFirstDay);
            } else if (DataSearchTypeEnum.SEARCH_TYPE_CURRENT_WEEK.getCode().equals(dataSearchTypeEnum.getCode())) {
                //当周
                LocalDate now = LocalDate.now();
                //DayOfWeek.SUNDAY以周日为第一天，DayOfWeek.MONDAY以周一为第一天
                LocalDate weekFirstDay = now.with(DayOfWeek.MONDAY);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String weeekFirstStr = weekFirstDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";
                clueIntentionGradeDataRequest.setStartTime(dateFormat.parse(weeekFirstStr));
            } else if (DataSearchTypeEnum.SEARCH_TYPE_CURRENT_DAY.getCode().equals(dataSearchTypeEnum.getCode())) {
                //当天
                LocalDate now = LocalDate.now();
                ZonedDateTime zonedDateTime = now.atStartOfDay(ZoneId.systemDefault());
                clueIntentionGradeDataRequest.setStartTime(Date.from(zonedDateTime.toInstant()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clueIntentionGradeDataRequest;
    }


    /**
     * 管理看板-任务看板
     * add by zly 2022-01-13
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public ClueTaskDataResponse getClueTaskData(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        //赋值租户，企微，经销商
        ClueAssembler.initClueIntentionGradeDataRequest(clueIntentionGradeDataRequest);
        log.info("管理看板-任务看板方法调用参数request={}", JSON.toJSONString(clueIntentionGradeDataRequest));
        String dealerId = clueIntentionGradeDataRequest.getDealerId();
        //实例化返回实体信息
        ClueTaskDataResponse clueTaskDataRes = new ClueTaskDataResponse();

        //1获取当前-待分配数量
        Integer distributeCount = 0;
        distributeCount = clueCustomerCollectService.getDistributeCount(clueIntentionGradeDataRequest);
        clueTaskDataRes.setDistributeCount(distributeCount);

        //2获取当前-待审批数量
        Integer approvelCount = 0;
        clueIntentionGradeDataRequest.setStatus(FailStatusEnum.APPROVAL_PENDING.getCode());
        approvelCount = clueFailService.getApprovelCount(clueIntentionGradeDataRequest);
        clueTaskDataRes.setApprovelCount(approvelCount);

        //开始结束时间赋值
        Instant currentDate = Instant.now();
        LocalDate localDate = YearMonth.from(currentDate.atZone(ZoneId.of("UTC"))).atDay(1);
        Date curentMonthFirstDay = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        //开始时间赋值当前月的第一天
        clueIntentionGradeDataRequest.setStartTime(curentMonthFirstDay);
        //结束时间赋值为当前时间
        clueIntentionGradeDataRequest.setEndTime(new Date());


        //3当月-逾期未跟进-分配逾期
        Integer noFollowUpDistributeCount = 0;
        clueIntentionGradeDataRequest.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
        clueIntentionGradeDataRequest.setIsFollowEmp(null);
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部计划表
            noFollowUpDistributeCount = oemCustomerFollowPlanService.getFollowUpData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商计划表
            noFollowUpDistributeCount = dealerCustomerFollowPlanService.getFollowUpData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setNoFollowUpDistributeCount(noFollowUpDistributeCount);


        //4当月-逾期未跟进-跟进逾期
        Integer noFollowUpExpireCount = 0;
        clueIntentionGradeDataRequest.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
        clueIntentionGradeDataRequest.setIsFollowEmp("1");
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部计划表
            noFollowUpExpireCount = oemCustomerFollowPlanService.getFollowUpData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商计划表
            noFollowUpExpireCount = dealerCustomerFollowPlanService.getFollowUpData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setNoFollowUpExpireCount(noFollowUpExpireCount);


        List<Integer> expireStatusList = new ArrayList<>();
        //5当月-逾期已跟进-分配逾期数量
        Integer followUpDistributeExpireCount = 0;
        clueIntentionGradeDataRequest.setStatus(FollowRecordStatusEnum.DISTRIBUTION.getCode());
        expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT.getCode());
        clueIntentionGradeDataRequest.setExpireStatusList(expireStatusList);
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部记录表
            followUpDistributeExpireCount = oemCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商记录表
            followUpDistributeExpireCount = dealerCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setFollowUpDistributeExpireCount(followUpDistributeExpireCount);


        //6当月-逾期已跟进-首跟逾期数量
        Integer followUpFirstCount = 0;
        expireStatusList = new ArrayList<>();
        clueIntentionGradeDataRequest.setStatus(FollowRecordStatusEnum.FOLLOW_UP.getCode());
        expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT_FIRST.getCode());
        clueIntentionGradeDataRequest.setExpireStatusList(expireStatusList);
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部记录表
            followUpFirstCount = oemCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商记录表
            followUpFirstCount = dealerCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setFollowUpFirstCount(followUpFirstCount);

        //7当月-逾期已跟进-跟进逾期数量
        expireStatusList = new ArrayList<>();
        clueIntentionGradeDataRequest.setStatus(FollowRecordStatusEnum.FOLLOW_UP.getCode());
        expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT.getCode());
        expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT_FIRST.getCode());
        clueIntentionGradeDataRequest.setExpireStatusList(expireStatusList);
        Integer followUpCount = 0;
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部记录表
            followUpCount = oemCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商记录表
            followUpCount = dealerCustomerFollowRecordService.getRecordFollowUpData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setFollowUpCount(followUpCount);

        //8历史逾期
        List<ClueTaskDataHistory> followUpHisoryList = null;
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //查询总部记录表
            followUpHisoryList = oemCustomerFollowRecordService.getRecordFollowUpHistoryData(clueIntentionGradeDataRequest);
        } else {
            //查询经销商记录表
            followUpHisoryList = dealerCustomerFollowRecordService.getRecordFollowUpHistoryData(clueIntentionGradeDataRequest);
        }
        clueTaskDataRes.setFollowUpHisoryList(followUpHisoryList);
        return clueTaskDataRes;
    }

    /**
     * 根据条件获取顾问新增线索数量
     * add by zly
     * 2022-01-15
     * @param clueDataRequest
     * @return
     */
    @Override
    public Long getEmpClueNumByTime(ClueIntentionGradeDataRequest clueDataRequest) {
        return clueManager.getEmpClueNumByTime(clueDataRequest);
    }

    /**
     * 根据条件获取顾问跟进下单线索
     * add by zly
     * 2022-01-16
     * @param clueDataRequest
     * @return
     */
    @Override
    public Long getEmpFollowOrderNum(ClueIntentionGradeDataRequest clueDataRequest) {
        return clueManager.getEmpFollowOrderNum(clueDataRequest);
    }

    /**
     * 根据条件查询顾问对应线索数量
     * add by zly
     * 2022-01-16
     * @param clueDataRequest
     * @return
     */
    @Override
    public Long getEmpNumByClueStatus(ClueIntentionGradeDataRequest clueDataRequest) {
        return clueManager.getEmpNumByClueStatus(clueDataRequest);
    }

    /**
     * 定时器执行-SCRM通过线索中心将线索下发给下游
     * scrm根据线索状态的规则配置，来定时捞历史跟进的线索数据，通过kafka发送给下游（包括scrm、会员积分、经纪人）
     * 其中scrm也来消费，然后通过接口的形式发送给crm(但是crm是外部系统，所以需要有一层scrm来消费，再调接口发送给crm)
     * 会员积分，经纪人是内部系统，scrm发送kafka，他们消费
     * add by zly
     * 2022-01-22
     * @return
     */
    @Override
    public void syncClueByMqToOther(String sysnTime) {
        String topic= KafkaConfig.customerSyncTopic;
        log.info("发送线索小心topic={}",topic);
        //去规则表里查看需要需要发送的租户和企微数据
        List<clueIssueConfigResponse> configList=clueManager.getConfigList();
        if(CollectionUtils.isEmpty(configList)){
            return ;
        }
        //根据配置循环拿数据
        configList.stream().forEach(config->{
            QueryClueRequest queryClueRequest=new QueryClueRequest();
            queryClueRequest.setTenantId(config.getTenantId());
            queryClueRequest.setCorpId(config.getCorpId());
            queryClueRequest.setFirstStatus(config.getClueStatus());
            queryClueRequest.setSecondStatus(config.getSecondStatus());
            queryClueRequest.setDeleted(DeleteEnum.INIT.getFlag());
            queryClueRequest.setSendMqStatus(RecordSendMqStatusEnum.SEND_NO.getCode());
            Integer count=clueManager.getclueCountByParam(queryClueRequest);
            if(count>0) {
                Integer pageSize = 5;
                queryClueRequest.setPageSize(pageSize);
                Integer pageTotal = (count % pageSize) > 0 ? (count / pageSize) + 1 : count / pageSize;
                for (int i = 0; i < pageTotal; i++) {
                    Integer pageStart = i * pageSize;
                    fixedThreadPool.execute(new Runnable() {
                        public void run() {
                            getcluePageByParam(queryClueRequest, pageStart);
                        }
                    });
                }
            }
        });
    }




    private void getcluePageByParam(QueryClueRequest queryClueRequest, Integer pageStart) {
        QueryClueRequest queryCluePageRequest= ClueDayStatsAssembler.transformPOToResponseVo(queryClueRequest,QueryClueRequest.class);
        queryCluePageRequest.setPageIndex(pageStart);
        log.info("每天定时同步线索信息到Mq--分页查看库里需要同步的数据queryCluePageRequest={},pageStart={}",JSON.toJSONString(queryCluePageRequest),pageStart);
        if(queryCluePageRequest.getFirstStatus()==FollowRecordStatusEnum.INIT.getCode()&&queryCluePageRequest.getSecondStatus()==FollowRecordSecondStatusEnum.INIT_INVALID.getCode()){
            //无效线索--只查记录表
            queryCluePageRequest.setIsFailClueRecord(null);
        }else{
            //有效线索--关联查询
            queryCluePageRequest.setIsFailClueRecord("isNo");
        }
        List<ClueToMqResponse> list=clueManager.queryCluePageRequest(queryCluePageRequest);
        log.info("每天定时同步线索信息到Mq--分页查看库里需要同步的数据list={}",JSON.toJSONString(list),pageStart);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        list.stream().forEach(c->{
            //发送kafka
            //获取经销商code,
            if(!StringUtils.isEmpty(c.getDealerId())) {
                Response<DealerResponse> dealerRes= mdQueryClient.getDetailById(Integer.parseInt(c.getDealerId()));
                if(dealerRes!=null&&dealerRes.getData()!=null){
                    DealerResponse dealer=dealerRes.getData();
                    c.setDealerCode(dealer.getCode());
                }
            }
            //根据到车系id拿车系code-对接org接口
            if(!StringUtils.isEmpty(c.getDriveSeriesId())) {
                QueryVehicleSeriesRequest seriesRequest = new QueryVehicleSeriesRequest();
                seriesRequest.setId(Long.valueOf(c.getDriveSeriesId()));
                Response<VehicleSeriesResponse> seriesRes = mdQueryClient.getOneSeriesByParam(seriesRequest);
                if (seriesRes != null && seriesRes.getData() != null) {
                    VehicleSeriesResponse serRes = seriesRes.getData();
                    c.setDriveVehicleSeriesCode(serRes.getCode());
                }
            }
            //根据试驾车型id拿车型code--对接org接口
            if(!StringUtils.isEmpty(c.getDriveModelId())) {
                QueryVehicleModelRequest modelRequest = new QueryVehicleModelRequest();
                modelRequest.setId(Long.valueOf(c.getDriveModelId()));
                Response<VehicleModelResponse> modelRes = mdQueryClient.getOneModelByParam(modelRequest);
                if (modelRes != null && modelRes.getData() != null) {
                    VehicleModelResponse model=modelRes.getData();
                    c.setDriveVehicleModelCode(model.getCode());
                }
            }
            //根据 车型id拿对应的年款和配置
            if(CollectionUtils.isNotEmpty(c.getIntentionVehicleList())){
                ClueToMqVehResponse clueVeh=c.getIntentionVehicleList().get(0);
                if(clueVeh!=null){
                    if(!StringUtils.isEmpty(clueVeh.getModelId())) {
                        QueryVehicleModelRequest modelRequest = new QueryVehicleModelRequest();
                        modelRequest.setId(Long.valueOf(clueVeh.getModelId()));
                        Response<VehicleModelResponse> modelRes = mdQueryClient.getOneModelByParam(modelRequest);
                        if (modelRes != null && modelRes.getData() != null) {
                            VehicleModelResponse model = modelRes.getData();
                            c.getIntentionVehicleList().get(0).setModelCode(model.getCode());
                            c.getIntentionVehicleList().get(0).setModelYearName(model.getAnnualModelName());//年款名称
                            c.getIntentionVehicleList().get(0).setModelYearCode(model.getYearCode());//年款code
                            c.getIntentionVehicleList().get(0).setConfigName(model.getConfigName());//配置名称
                            c.getIntentionVehicleList().get(0).setConfigCode(model.getConfigCode());//配置code
                        }
                    }
                    if(!StringUtils.isEmpty(clueVeh.getSeriesId())) {
                        QueryVehicleSeriesRequest seriesRequest = new QueryVehicleSeriesRequest();
                        seriesRequest.setId(Long.valueOf(clueVeh.getSeriesId()));
                        Response<VehicleSeriesResponse> seriesRes = mdQueryClient.getOneSeriesByParam(seriesRequest);
                        if (seriesRes != null && seriesRes.getData() != null) {
                            VehicleSeriesResponse serRes = seriesRes.getData();
                            c.getIntentionVehicleList().get(0).setSeriesCode(serRes.getCode());
                        }
                    }

                }
            }


            //跟进人手机号查询
            if(!StringUtils.isEmpty(c.getFollowEmpId())){
                Response<EmployeeResponse> empRes=  mdQueryClient.getByIdWithOutRole(Long.valueOf(c.getFollowEmpId()));
                if(empRes!=null&&empRes.getData()!=null) {
                    EmployeeResponse emp=empRes.getData();
                    c.setFollowEmpPhone(emp.getMobile());
                }
            }

            //战败原因处理
           String failReason= c.getClueFailReasonList();
            AtomicReference<String> failReasonStr= new AtomicReference<>("");
            if(!StringUtils.isEmpty(failReason)){
                Arrays.stream(failReason.split(",")).forEach(r->{
                    failReasonStr.set(failReasonStr+ FailReasonEnum.getDictionaries(r));
                });

            }
            log.info("每天定时同步线索信息到Mq--战败原因，failReason={},转换后failReasonStr={}",failReason,failReasonStr);
            c.setClueFailReasonList(failReasonStr.get());
            c.setUuId(UUID.randomUUID().toString());
            log.info("每天定时同步线索信息到Mq--分页查看库里需要同步的数据,同步到mq的数据={}",JSON.toJSONString(c));
            kafkaService.send(KafkaConfig.customerSyncTopic,c);
            //只同步交车，战败的给crm
            if(!StringUtils.isEmpty(c.getCrmClueId())&&(FollowRecordSecondStatusEnum.FOLLOW_DELIVERY.getCode()==c.getClueStatus()||
                FollowRecordSecondStatusEnum.APPROVAL_FAIL_AGREE.getCode()==c.getClueStatus()||
                    FollowRecordSecondStatusEnum.APPROVAL_FAIL_ACTIVATE.getCode()==c.getClueStatus())) {
                SyncCrmUpdateClueRequest request = changeClueParamToCrmUpdate(c);
                if(Objects.nonNull(request)){
                    crmService.clueInitialDataToCrmUpdate(request);
                }
            }

        });
    }


    private SyncCrmUpdateClueRequest changeClueParamToCrmUpdate(ClueToMqResponse c) {
        ClueToMqVehResponse veh=null;
        if(CollectionUtils.isNotEmpty(c.getIntentionVehicleList())){
            veh=c.getIntentionVehicleList().get(0);
        }
        Integer clueStatus=null;
        //身份证信息
        CertificateInfoResponse certificateInfoResponse = null;
        //发票信息
        PurchaseInvoiceInfo purchaseInvoiceInfo = null;
        //交车
        if(FollowRecordSecondStatusEnum.FOLLOW_DELIVERY.getCode()==c.getClueStatus()){
            clueStatus= CrmStatusEnum.crm_status_22.getCode();

            //查询交车证件信息
            QueryCertificateInfoRequest queryCertificateInfoRequest = new QueryCertificateInfoRequest();
            queryCertificateInfoRequest.setOneId(Long.valueOf(c.getOneId()));
            queryCertificateInfoRequest.setDeleted(DeleteEnum.INIT.getFlag());
            queryCertificateInfoRequest.setCertificateType(CertificateEnum.ID_CARD.getCode());
            log.info("定时器调用crm接口进行线索修改 调用mdQuery 查询证件表,入参：{}", JsonUtils.object2JSON(queryCertificateInfoRequest));
            certificateInfoResponse = mdQueryClient.getOneByParam(queryCertificateInfoRequest).getData();
            log.info("定时器调用crm接口进行线索修改 调用mdQuery 查询证件表，返回数据：【{}】",JSON.toJSONString(certificateInfoResponse));

            //查询发票信息
            PurchaseInvoiceInfo queryPurchaseInvoiceInfo = new PurchaseInvoiceInfo();
            queryPurchaseInvoiceInfo.setDeleted(DeleteEnum.INIT.getFlag());
            queryPurchaseInvoiceInfo.setOrderId(c.getOrderId());
            purchaseInvoiceInfo = purchaseInvoiceInfoService.getOneByParam(queryPurchaseInvoiceInfo);

            if(certificateInfoResponse == null || purchaseInvoiceInfo == null){
                log.error("定时器调用crm接口进行线索修改，查询证件信息或者发票信息为空，证件信息：【{}】，发票信息：【{}】，线索数据：【{}】",
                        JSON.toJSONString(certificateInfoResponse),JSON.toJSONString(purchaseInvoiceInfo),JSON.toJSONString(c));
                return null;
            }
        }
        //战败
        if(FollowRecordSecondStatusEnum.APPROVAL_FAIL_AGREE.getCode()==c.getClueStatus()){
            clueStatus=CrmStatusEnum.crm_status_9.getCode();
        }
        //战败激活--已分配
        if(FollowRecordSecondStatusEnum.APPROVAL_FAIL_ACTIVATE.getCode()==c.getClueStatus()){
            clueStatus=CrmStatusEnum.crm_status_7.getCode();
        }
        SyncCrmUpdateClueRequest dataToCrm=SyncCrmUpdateClueRequest.builder()
                .recordId(c.getRId())
                .crmLeadId(c.getCrmClueId())//CRM线索ID y
                .leadStatus(clueStatus)//线索状态 y
                .phone(c.getPhone())//客户手机号
                .name(c.getName())
                //.invoiceNo("")//发票号码
                //.credentialType(1)//证件类型:1.身份证 ; 2.军官证 ; 3.港澳台海外地区证件;  4.企业代码证
                //.credentialNumber("420321")//证件号不能为空
                .defeatRemark(c.getClueFailRemark())//战败备注
                .defeatReason(c.getClueFailReasonList())//战败原因 FailReasonEnum
                .deliveryDate(DateUtil.toDateString(c.getDriveVehicleTime(), DateUtil.DEFAULT_DATE_PATTERN))//交车日期
                .dealerCode(c.getDealerCode())//经销商code y
                .mobile(c.getFollowEmpPhone())//传跟进人的手机号 y
                .seriesCode(veh==null?"":veh.getSeriesCode())//意向车型CODE是SCRM的车系code
                .seriesName(veh==null?"":veh.getSeriesName())//车型名称
                .modelCode(veh==null?"":veh.getModelYearCode())
                .modelName(veh==null?"":veh.getModelYearName())//年款名称
                .rangeCode(veh==null?"":veh.getConfigCode())
                .rangeName(veh==null?"":veh.getConfigName())//版型名称
                .loseType(clueStatus==CrmStatusEnum.crm_status_9.getCode()?defaultFailType:null)
                .build();
        if(FollowRecordSecondStatusEnum.FOLLOW_DELIVERY.getCode()==c.getClueStatus()){
            dataToCrm.setInvoiceNo(purchaseInvoiceInfo.getInvoiceNum());
            dataToCrm.setCredentialType(1);
            dataToCrm.setCredentialNumber(certificateInfoResponse.getCardId());
        }

        return dataToCrm;
    }

    /**
     * 根据 crm的状态转化成scrm的线索状态
     * 将CRM中线索状态为1-新建、2-已下发、3-已撞单、4-已失效 、5-已拒绝 、
     * 16-已回访 、17-自测 、20-申请失效 、21-待下发、13-已报价
     * 状态迁移后全部转为 已战败状态
     *
     * 他们真实际的战败不做标识
     * @param leadStatus
     * @return
     */
    @Override
    public Integer initClueInitStatus(Integer leadStatus) {
        if(CrmStatusEnum.crm_status_1.getCode()==leadStatus||
                CrmStatusEnum.crm_status_2.getCode()==leadStatus||
                CrmStatusEnum.crm_status_3.getCode()==leadStatus||
                CrmStatusEnum.crm_status_4.getCode()==leadStatus||
                CrmStatusEnum.crm_status_5.getCode()==leadStatus||
                CrmStatusEnum.crm_status_13.getCode()==leadStatus||
                CrmStatusEnum.crm_status_16 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_17 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_19 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_20.getCode()==leadStatus||
                CrmStatusEnum.crm_status_21.getCode()==leadStatus

        ){
            return ClueStatsEnum.IS_FAIL.getCode();
        }
        return null;
    }
    /**
     * 根据 crm的状态转化成scrm的线索状态
     * @param leadStatus
     * @return
     */
    @Override
    public Integer initClueStatus(Integer leadStatus) {
        if(CrmStatusEnum.crm_status_6.getCode()==leadStatus||
                CrmStatusEnum.crm_status_7.getCode()==leadStatus||
                CrmStatusEnum.crm_status_10.getCode()==leadStatus||
                CrmStatusEnum.crm_status_11 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_12 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_18.getCode()==leadStatus){
            return ClueStatsEnum.FOLLOW_UP.getCode();
        }else if(CrmStatusEnum.crm_status_8.getCode()==leadStatus){
            return ClueStatsEnum.FAIL_APPROVE.getCode();
        }else if(CrmStatusEnum.crm_status_1.getCode()==leadStatus||
                CrmStatusEnum.crm_status_2.getCode()==leadStatus||
                CrmStatusEnum.crm_status_3.getCode()==leadStatus||
                CrmStatusEnum.crm_status_4.getCode()==leadStatus||
                CrmStatusEnum.crm_status_5.getCode()==leadStatus||
                CrmStatusEnum.crm_status_9.getCode()==leadStatus||
                CrmStatusEnum.crm_status_13.getCode()==leadStatus||
                CrmStatusEnum.crm_status_16 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_17 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_19 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_20.getCode()==leadStatus||
                CrmStatusEnum.crm_status_21.getCode()==leadStatus
       ){
            return ClueStatsEnum.IS_FAIL.getCode();
        }else if(CrmStatusEnum.crm_status_14.getCode()==leadStatus){
            return ClueStatsEnum.ORDER.getCode();
        }else if(CrmStatusEnum.crm_status_15.getCode()==leadStatus){
            return ClueStatsEnum.CONSUMED.getCode();
        }else if(CrmStatusEnum.crm_status_22.getCode()==leadStatus){
            return ClueStatsEnum.DELIVERY.getCode();
        }
        return null;
    }

    /**
     * crm的状态，转化成线索记录的状态
     * @param leadStatus
     * @return
     */
    public Integer initRecordStatus(Integer leadStatus) {
        if(CrmStatusEnum.crm_status_9.getCode()==leadStatus||
                CrmStatusEnum.crm_status_11 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_12 .getCode()==leadStatus||
                CrmStatusEnum.crm_status_15.getCode()==leadStatus||
                CrmStatusEnum.crm_status_22.getCode()==leadStatus){
            return FollowRecordStatusEnum.FOLLOW_UP.getCode();
        }
        return null;
    }

    /**
     * crm的状态，转化成线索记录的二级状态
     * @param leadStatus
     * @return
     */
    public Integer initSecondRecordStatus(Integer leadStatus, ScrmLead scrmLead) {
        if(CrmStatusEnum.crm_status_9.getCode()==leadStatus){
            return FollowRecordSecondStatusEnum.APPROVAL_FAIL_AGREE.getCode();
        }else if(CrmStatusEnum.crm_status_11 .getCode()==leadStatus){
            return FollowRecordSecondStatusEnum.FOLLOW_DRIVE_APPOINT.getCode();
        }else if(CrmStatusEnum.crm_status_12 .getCode()==leadStatus){
            return FollowRecordSecondStatusEnum.FOLLOW_DRIVE_TEST.getCode();
        }else if(CrmStatusEnum.crm_status_15 .getCode()==leadStatus){
            return FollowRecordSecondStatusEnum.FOLLOW_CONSUMED.getCode();
        }else if(CrmStatusEnum.crm_status_22.getCode()==leadStatus){
            return FollowRecordSecondStatusEnum.FOLLOW_DELIVERY.getCode();
        }
        return null;
    }

    /**
     * 根据从crm视图同步过来的线索状态修改线索信息
     * add by zly
     * 2022-01-29
     * @param lead
     */
    @Override
    public void sysnClueStatusFromMq(ScrmLead lead) {
        //将crm状态转化成scrm的线索状态，若返回空，则转化失败，不做线索修改
        Integer clueStatus=this.initClueStatus(lead.getLeadStatus());
        if(clueStatus==null){
            return;
        }

        //根据crmId查看Scrm是否存在对应的线索，若不存在，则不做线索修改
        Clue clue=new Clue();
        clue.setCrmClueId(lead.getLeadId().toString());
        clue=clueManager.getOneByParam(clue);
        if(clue==null){
            return;
        }
        //查看Scrm的线索状态是否和转化后的crm状态一致，若是一致，说明不需要修改线索状态
        if(clue.getStatus()==clueStatus){
            return;
        }

        //查看线索是否属于指定的经销商，如果是，则不更新crm同步过来的战败,交车信息
        Integer secondRecordStatus=initSecondRecordStatus(lead.getLeadStatus(),lead);
        if(!StringUtils.isEmpty(defaultDealerId)){
            String clueDealerId=clue.getDealerId()+"";
            Long count= Arrays.stream(defaultDealerId.split(",")).filter(str-> clueDealerId.equals(str)).count();
            //查看同步过来的数据是否属于战败，交车，若是，则不处理
            if(count>0&&(secondRecordStatus==FollowRecordSecondStatusEnum.APPROVAL_FAIL_AGREE.getCode()||
               secondRecordStatus==FollowRecordSecondStatusEnum.FOLLOW_DELIVERY.getCode())){
                return;
            }
        }

        //线索赋值crm同步过来的状态，进行修改
        clue.setStatus(clueStatus);
        if(lead.getReceiveDate()!=null) {
            clue.setActualSalesTime(lead.getReceiveDate());
        }
        int count=clueManager.updateClueStatus(clue);
        if(count==0){
           return;
        }



        //获取线索对应得客户信息
        QueryCustomerRequest customerRequest=new QueryCustomerRequest();
        customerRequest.setId(clue.getCusId());
        CustomerResponse customerRes=dealerCustomerService.getOneByParam(customerRequest);
        Date currentDate=new Date();
        //修改同步过来的线索对应的 意向信息（ 意向车型CODE,意向车型名称, 年款CODE,年款名称,版型CODE/配置,版型名称/配置
       // List<ClueIntentionVehicle> vehList=new ArrayList<>();
       // ClueIntentionVehicle clueVeh=new ClueIntentionVehicle();
        /*if(!StringUtils.isEmpty(lead.getSeriesName())||!StringUtils.isEmpty(lead.getModelName())||
           !StringUtils.isEmpty(lead.getRangeName())){

            clueVeh.setClueId(clue.getId());
            //根据车系名称拿对应的code 和id
            if(!StringUtils.isEmpty(lead.getSeriesName())) {
                QueryVehicleSeriesRequest seriesRequest=new QueryVehicleSeriesRequest();
                seriesRequest.setName(lead.getSeriesName());
                seriesRequest.setTenantId(tenandId);
                seriesRequest.setCorpId(corpId);
                seriesRequest.setStatus(DeleteEnum.INIT.getFlag());
                //根据车系名称拿到车系id
                Response<VehicleSeriesResponse> seriesRes=mdQueryClient.getOneSeriesByParam(seriesRequest);
                if(seriesRes!=null&&seriesRes.getData()!=null){
                    VehicleSeriesResponse serRes=seriesRes.getData();
                    clueVeh.setSeriesName(serRes.getName());
                    clueVeh.setSeriesCode(serRes.getCode());
                    clueVeh.setSeriesId(serRes.getId().toString());
                    collectRequest.setSeriesId(serRes.getId().toString());
                }
            }

            //他们有车系，配置和年款 ,配置和年款拼接就成了车型
            //根据crm年款modelName ，配置name  拿对应的车型id,名称
            if(!StringUtils.isEmpty(lead.getRangeName())&&!StringUtils.isEmpty(lead.getModelName())){
                //根据配置code,年款code,获得配置id
                QueryVehicleModelRequest configRequest = new QueryVehicleModelRequest();
                configRequest.setAnnualModelName(lead.getModelName());//年款名称
                configRequest.setConfigName(lead.getRangeName());//配置名称
                configRequest.setTenantId(tenandId);
                configRequest.setCorpId(corpId);
                configRequest.setStatus(DeleteEnum.INIT.getFlag());
                Response<VehicleModelResponse> configRes = mdQueryClient.getOneModelByParam(configRequest);
                if (configRes != null && configRes.getData() != null) {
                    VehicleModelResponse vehModel=configRes.getData();
                    clueVeh.setModelName(vehModel.getName());
                    clueVeh.setModelCode(vehModel.getCode());
                    clueVeh.setModelId(vehModel.getId().toString());
                    collectRequest.setModelId(vehModel.getId().toString());
                }
            }
            //新增线索意向信息
            clueVeh.setTenantId(clue.getTenantId());
            clueVeh.setCorpId(clue.getCorpId());
            clueVeh.setDealerId(clue.getDealerId());
            clueVeh.setDeleted(DeleteEnum.INIT.getFlag());
            clueVeh.setStatus(StatusEnum.TEMP_STOR.getCode());
            clueIntentionVehicleService.insert(clueVeh);
            vehList.add(clueVeh);
        }*/
        //新增记录,需求说的同步，试驾，交车，战败数据过来，但是他们没有试驾，有待试驾，所以同步的待试驾，他们的待试驾对应我们的二级试驾预约
        AddCustomerFollowRecordRequest record=new AddCustomerFollowRecordRequest();
        record.setClueId(clue.getId());
        record.setTenantId(clue.getTenantId());
        record.setCorpId(clue.getCorpId());
        record.setDealerId(clue.getDealerId());
        record.setCusId(clue.getCusId());
        if(customerRes!=null) {
            record.setFollowEmpId(customerRes.getFollowEmpId());
            record.setFollowEmpName(customerRes.getFollowEmpName());
        }
        if(lead.getReceiveDate()!=null){
            record.setOperateTime(lead.getReceiveDate());
        }
        //如果同步状态有变，这里要跟着变
        record.setStatus(initRecordStatus(lead.getLeadStatus()));
        record.setSecondStatus(secondRecordStatus);
        record.setCreatedBy("CRM");
        record.setCreatedName("CRM");
        record.setCreatedTime(currentDate);

       /* if(CollectionUtils.isNotEmpty(vehList)) {
            record.setVehInfo(JSON.toJSONString(vehList));
        }*/
        //查看对应的客户信息
        CustomerResponse customerResponse=dealerCustomerService.getDetailById(clue.getCusId());
        CustomerSourceInfo customerSourceInfo=CustomerExtAssembler.transformVOToPO(customerResponse,CustomerSourceInfo.class);
        record.setSourceInfo(JSON.toJSONString(customerSourceInfo));
       //查看线索意向信息
        ClueIntention request=new ClueIntention();
        request.setClueId(clue.getId());
        ClueIntentionResponse  clueIntentionRes= clueIntentionService.getOneByParam(request);
        if(clueIntentionRes!=null) {
           ClueIntention clueIntention = ClueIntentionAssembler.transformPOToResponseVo(clueIntentionRes, ClueIntention.class);
           record.setIntentionTags(clueIntentionService.getClueIntentionStr(clueIntention));
        }

        if(FollowRecordSecondStatusEnum.FOLLOW_DRIVE_APPOINT.getCode()==record.getSecondStatus()){
            //获取线索源信息、
            ClueInitial initialRequest=new ClueInitial();
            initialRequest.setId(clue.getId());
            ClueInitial initialRes=clueInitialService.getOneclueInitialByParam(initialRequest);
            if(initialRes!=null&&initialRes.getAccessAddTime()!=null) {
                //只有待试驾的需要计划跟进，对应的计划跟进是试乘试驾？
                AddCustomerFollowPlanRequest plan = new AddCustomerFollowPlanRequest();
                plan.setClueId(clue.getId());
                plan.setTenantId(clue.getTenantId());
                plan.setCorpId(clue.getCorpId());
                plan.setDealerId(clue.getDealerId());
                plan.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
                plan.setCreatedBy("crm-kafka-sync");
                plan.setCreatedName("crm-kafka-sync");
                plan.setCreatedTime(currentDate);
                plan.setCusId(clue.getCusId());
                plan.setPlanFollowContent(String.valueOf(FollowContentEnum.DRIVE_TEST.getCode()));
                //Date planFollowTime = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
                plan.setPlanFollowTime(initialRes.getAccessAddTime());
                Long planId = dealerCustomerFollowPlanService.insert(plan);
                record.setNextFollowPlanId(planId);
            }
        }
        dealerCustomerFollowRecordService.insert(record);
        //最后，更新宽表信息
        //查看跟进次数
        ClueCustomerCollect queryClueCollect = new ClueCustomerCollect();
        queryClueCollect.setClueId(clue.getId());
        queryClueCollect.setDeleted(DeleteEnum.INIT.getFlag());
        ClueCustomerCollect exist = clueCustomerCollectService.getOneByParam(queryClueCollect);
        if(exist!=null){
            ClueCustomerCollect collectRequest=new ClueCustomerCollect();
            collectRequest.setClueId(clue.getId());
            collectRequest.setClueStatus(clue.getStatus());
            if(lead.getReceiveDate()!=null) {
                collectRequest.setDeliveryCreatedTime(lead.getReceiveDate());
            }
            collectRequest.setFollowNum(exist.getFollowNum() == null ? 1 : exist.getFollowNum() + 1);
            clueCustomerCollectService.updateByClueId(collectRequest);
        }

        ClueIntentionVehicle clueVehRequest=new ClueIntentionVehicle();
        clueVehRequest.setClueId(clue.getId());
        ClueIntentionVehicle clueVeh=clueIntentionVehicleService.getOneByParam(clueVehRequest);
        //埋点(代试驾-试乘试驾、交车、实销、战败审核同意)
        syncClueBuriedPintService.clueBuriedPint(lead, clue, clueVeh);
    }


}
